package com.ugoodtech.mdcc.client.service.impl;

import com.google.common.collect.Lists;
import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.domain.PerformanceReportDetail;
import com.ugoodtech.mdcc.core.domain.QPerformanceReportDetail;
import com.ugoodtech.mdcc.core.domain.QUserProfile;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.domain.UserProfile;
import com.ugoodtech.mdcc.core.repository.PerformanceReportDetailRepository;
import com.ugoodtech.mdcc.core.repository.UserProfileRepository;
import com.ugoodtech.mdcc.client.common.BizConstants;
import com.ugoodtech.mdcc.client.exception.BizException;
import com.ugoodtech.mdcc.client.exception.EnumBizError;
import com.ugoodtech.mdcc.client.dto.PerformanceReportBrandVO;
import com.ugoodtech.mdcc.client.dto.PerformanceReportComparisonVO;
import com.ugoodtech.mdcc.client.dto.PerformanceReportCustomerVO;
import com.ugoodtech.mdcc.client.dto.PerformanceReportSalesVO;
import com.ugoodtech.mdcc.client.dto.PerformanceReportStatisticVersionVO;
import com.ugoodtech.mdcc.client.dto.PerformanceReportStatisticsResponse;
import com.ugoodtech.mdcc.client.service.PerformanceReportStatisticsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by Mario on 2020/2/19.
 *
 * @author Mario
 */
@Service
@Slf4j
public class PerformanceReportStatisticsServiceImpl implements PerformanceReportStatisticsService {

	@Resource
	private PerformanceReportDetailRepository performanceReportDetailRepository;

	@Autowired
	private UserProfileRepository userProfileRepository;


	/**
	 * 获取业绩报告数据统计列表接口
	 * @param brandTypeList 名牌类型
	 * @param customerTypeList 客户类型
	 * @param name 客户名称
	 * @param monthList 月份
	 * @param year 年
	 * @param departmentList 部门
	 * @param provinceList 省份
	 * */
	@Override
	public PerformanceReportStatisticsResponse
	getPerformanceReportStatistics(List<Integer> brandTypeList, List<Integer> customerTypeList,
								   String name, List<Integer> monthList, Integer year, List<Long> departmentList,
								   List<Long> provinceList,List<Long> brandList,
								   List<Long> userProvinceList,List<Long> userBrandList){
		List<PerformanceReportDetail> performanceReportDetailList = new ArrayList<>();
		performanceReportDetailList = this.getPerformanceReportDetailList(brandTypeList, customerTypeList, name,monthList, year, departmentList, provinceList,userProvinceList,brandList,userBrandList);//根据输入的品牌、客户类型、月份、年份、省份、部门、名称关键字获取业绩报告具体信息

		if(log.isDebugEnabled()){
			log.info("根据传入的品牌、客户类型、客户名字、月份、年、部门、省份关键字，查询performanceReport表[{}]", performanceReportDetailList);
		}
		List<PerformanceReportSalesVO> performanceReportSalesList = new ArrayList<>();
		List<PerformanceReportBrandVO> performanceReportBrandList =  new ArrayList<>();
		List<PerformanceReportCustomerVO> performanceReportCustomerList = new ArrayList<>();
		List<PerformanceReportComparisonVO> performanceReportComparisonList = new ArrayList<>();
		if(performanceReportDetailList != null && performanceReportDetailList.size() != 0){
			performanceReportSalesList = this.getPerformanceReportSalesList(performanceReportDetailList);//封装根据销售人员排的净销售额指标
			if(log.isDebugEnabled()){
				log.info("按销售人员分类获取净销售额指标[{}]", performanceReportSalesList );
			}
			performanceReportBrandList = this.getPerformanceReportBrandList(performanceReportDetailList);//封装根据品牌排的净销售额指标
			if(log.isDebugEnabled()){
				log.info("按品牌分类获取净销售额指标[{}]", performanceReportBrandList);
			}
			performanceReportCustomerList = this.getPerformanceReportCustomerList(performanceReportDetailList);//封装根据客户类型排的净销售额指标
			if(log.isDebugEnabled()){
				log.info("按客户类型后去净销售额指标[{}]", performanceReportCustomerList);
			}
			year = year -1 ;
			List<PerformanceReportDetail> performanceReportDetailFormerList = new ArrayList<>();
			performanceReportDetailFormerList = this.getPerformanceReportDetailList(brandTypeList, customerTypeList, name,monthList, year, departmentList, provinceList,userProvinceList,brandList,userBrandList);//查输入年份前一年的业绩报告具体信息
			if(log.isDebugEnabled()){
				log.info("根据传入的查询条件，获取前一年performanceReport表数据[{}]", performanceReportDetailFormerList);
			}
			performanceReportComparisonList = this.getPerformanceReportComparisonList(performanceReportDetailList,performanceReportDetailFormerList);//封装根据年份排的各品牌各客户类型的净销售额指标
			if(log.isDebugEnabled()){
				log.info("按年份分类计算各品牌中的各客户类型的选中年份的总销售额和前一年的总销售额以及年增长率", performanceReportComparisonList);
			}
		}
		PerformanceReportStatisticsResponse performanceReportStatisics = new PerformanceReportStatisticsResponse();
		performanceReportStatisics.setPerformanceReportSales(performanceReportSalesList);
		performanceReportStatisics.setPerformanceReportBrand(performanceReportBrandList);
		performanceReportStatisics.setPerformanceReportCustomer(performanceReportCustomerList);
		performanceReportStatisics.setPerformanceReportComparison(performanceReportComparisonList);
		return performanceReportStatisics;
	}

	//根据输入的品牌、客户类型、月份、年份、省份、部门、名称关键字搜索出来的内容查副表performance_report_detail表
	public List<PerformanceReportDetail> getPerformanceReportDetailList(List<Integer> brandTypeList, List<Integer> customerTypeList, String name, List<Integer> monthList, Integer year,
																		List<Long> departmentList,
																		List<Long> provinceList,//查询的省市id列表
																		List<Long> userProvinceList,//用户省市id列表
																		List<Long> brandList,//查询的品牌列表
																		List<Long> userBrandList){//用户品牌列表
		List<PerformanceReportDetail> performanceReportDetailDOList = new ArrayList<>();
		List<String> nameList = new ArrayList<>();
		if(departmentList.size() >= 1 || provinceList.size() >= 1 || !name.equals("")|| brandList.size() >= 1){//根据省份、部门和人名，查这个员工存不存在，如果员工不存在，则直接不查数据库
			QUserProfile qUserProfile =QUserProfile.userProfile;
			BooleanBuilder booleanBuilder =new BooleanBuilder();
			if (departmentList.size()!=0){
				booleanBuilder.and(qUserProfile.departmentList.any().id.in(departmentList));
			}
			if (provinceList.size()==0 && brandList.size()==0){//省份==“” && 品牌==“”
				// 部门 and (省份=A or 品牌=B )
				booleanBuilder.and(qUserProfile.nationList.any().id.in(userProvinceList).or(qUserProfile.brandList.any().id.in(userBrandList)));
			}else {
				//省份 ！= null && 省份 不包含 你的省份) && (品牌 ！= null && 品牌 不包含 你的品牌
				if (userProvinceList.size()!=0 && userBrandList.size()!=0){
					if ((provinceList.size()!=0&& !isEq(provinceList,userProvinceList) )&& (brandList.size()!=0&& !isEq(brandList,userBrandList))){
						return new ArrayList<>();
					}
				}
				if (provinceList.size()==0 ){
					// 省份 = 你的省份
					//品牌 包含 你的品牌 省份== 你的省份
					if (isEq(brandList,userBrandList)){
						if (userProvinceList.size()!=0){
							booleanBuilder.and(qUserProfile.nationList.any().id.in(userProvinceList));
						}
						booleanBuilder.and(qUserProfile.brandList.any().id.in(userBrandList));
					}else {
						if (userBrandList.size()==0){//用户没有品牌就代表所有品牌
							if (userProvinceList.size()!=0){
								booleanBuilder.and(qUserProfile.nationList.any().id.in(userProvinceList).or(qUserProfile.brandList.any().id.in(brandList)));
							}else {
								booleanBuilder.and(qUserProfile.brandList.any().id.in(brandList));
							}
						}else {
							if (userProvinceList.size()!=0){
								booleanBuilder.and(qUserProfile.nationList.any().id.in(userProvinceList));
							}
							booleanBuilder.and(qUserProfile.brandList.any().id.in(brandList));
						}
					}
				}else {
					//用户省份=0代表所有省份
					if (userProvinceList.size()==0){
						//品牌 == “”
						if (brandList.size()==0){
							booleanBuilder.and(qUserProfile.nationList.any().id.in(provinceList));
						}else {
							//品牌 包含 你的品牌 省份== 你的省份
							if (isEq(brandList,userBrandList)){
								booleanBuilder.and(qUserProfile.nationList.any().id.in(provinceList));
								booleanBuilder.and(qUserProfile.brandList.any().id.in(brandList));
							}else {
								//品牌 不包含 你的品牌 省份== 你的省份
								//上海奥迪 ==上海下的奥迪
								if (userBrandList.size()==0){//用户没有品牌就代表所有品牌
									booleanBuilder.and(qUserProfile.nationList.any().id.in(provinceList).or(qUserProfile.brandList.any().id.in(brandList)));
								}else {
									booleanBuilder.and(qUserProfile.nationList.any().id.in(provinceList));
									booleanBuilder.and(qUserProfile.brandList.any().id.in(userBrandList));
								}

							}
						}
					}else {
						// 省份 包含 你的省份
						if (  isEq(provinceList,userProvinceList)){
							//品牌 == “”
							if (brandList.size()==0){
								booleanBuilder.and(qUserProfile.nationList.any().id.in(provinceList));

							}else {
								//品牌 包含 你的品牌 省份== 你的省份
								if (isEq(brandList,userBrandList)){
									booleanBuilder.and(qUserProfile.nationList.any().id.in(provinceList));
									booleanBuilder.and(qUserProfile.brandList.any().id.in(brandList));
								}else {
									//品牌 不包含 你的品牌 省份== 你的省份
									//上海奥迪 ==上海下的奥迪
									if (userBrandList.size()==0){//用户没有品牌就代表所有品牌
										booleanBuilder.and(qUserProfile.nationList.any().id.in(userProvinceList).or(qUserProfile.brandList.any().id.in(brandList)));
									}else {
										booleanBuilder.and(qUserProfile.nationList.any().id.in(provinceList));
										booleanBuilder.and(qUserProfile.brandList.any().id.in(userBrandList));
									}

								}
							}
						}else {
							//省份 不包含 你的省份
							//品牌 == “”
							if (brandList.size()==0){
								//查询本品牌内那个地区的数据
								booleanBuilder.and(qUserProfile.nationList.any().id.in(provinceList))
										.and(qUserProfile.brandList.any().id.in(userBrandList));
							}else {
								//查询本品牌内那个地区的数据
								booleanBuilder.and(qUserProfile.nationList.any().id.in(provinceList))
										.and(qUserProfile.brandList.any().id.in(userBrandList));
							}
						}
					}

				}
			}

			if (!"".equals(name)){
				booleanBuilder.and(qUserProfile.realName.eq(name));
			}else {
				//如果用户的省份或者用户的品牌为空，代表所有省份或者品牌
				if (userProvinceList.size()==0|| userBrandList.size()==0){
					User currentUser = getCurrentUser();
					if (currentUser!=null){
						booleanBuilder.or(qUserProfile.user.id.eq(currentUser.getId()));
					}else {
						UserProfile userProfile = userProfileRepository.findByUserId(571l);
						booleanBuilder.or(qUserProfile.user.id.eq(userProfile.getUser().getId()));
					}
				}
			}
			System.out.println("查询条件=="+booleanBuilder.toString());
			Iterable<UserProfile> all = userProfileRepository.findAll(booleanBuilder);
			List<UserProfile> users  = Lists.newArrayList(all);
			for(UserProfile user : users){
				nameList.add(user.getRealName());
			}
			if(nameList.size() !=0 && nameList != null){
				performanceReportDetailDOList = getPerformanceReportDetails(brandTypeList, customerTypeList, monthList, year, nameList);

				log.info("根据传入的品牌类型[{}]、 客户类型[{}]、 月份[{}]、 部门筛选后的员工姓名[{}]查performanceReportDetail表，得到数据[{]]",brandTypeList,customerTypeList,monthList,nameList,performanceReportDetailDOList);
			}
		}else {

			performanceReportDetailDOList = getPerformanceReportDetails(brandTypeList, customerTypeList, monthList, year, nameList);
			log.info("根据传入的品牌类型[{}]、 客户类型[{}]、 月份[{}]、 部门筛选后的员工姓名[{}]查performanceReportDetail表，得到数据[{]]",brandTypeList,customerTypeList,monthList,nameList,performanceReportDetailDOList);
		}
		Map<PerformanceReportStatisticVersionVO, PerformanceReportDetail> performanceReportStatisticVersionVOMap = new HashMap<>(16);
		for(PerformanceReportDetail performanceReportDetailDO : performanceReportDetailDOList){//取最大版本号的数据
			PerformanceReportStatisticVersionVO performanceReportStatisticVersionVO =  new PerformanceReportStatisticVersionVO();//开始暂存除版本号外的数据到类中
			if(null != performanceReportDetailDO.getCustomerType()){
				performanceReportStatisticVersionVO.setCustomerType(performanceReportDetailDO.getCustomerType());
			}
			if(null != performanceReportDetailDO.getBrandType()){
				performanceReportStatisticVersionVO.setBrandType(performanceReportDetailDO.getBrandType());
			}
			if(null != performanceReportDetailDO.getStatus()){
				performanceReportStatisticVersionVO.setStatus(performanceReportDetailDO.getStatus());
			}
			if(null != performanceReportDetailDO.getEmployeeName()){
				performanceReportStatisticVersionVO.setEmployeeName(performanceReportDetailDO.getEmployeeName());
			}
			if(null != performanceReportDetailDO.getYear()){
				performanceReportStatisticVersionVO.setYear(performanceReportDetailDO.getYear());
			}
			if(null != performanceReportDetailDO.getMonth()){
				performanceReportStatisticVersionVO.setMonth(performanceReportDetailDO.getMonth());
			}
			if(!performanceReportStatisticVersionVOMap.containsKey(performanceReportStatisticVersionVO)){//如果没有一模一样的数据，那么直接存到Map中去
				performanceReportStatisticVersionVOMap.put(performanceReportStatisticVersionVO, performanceReportDetailDO);
			}else {//如果有一模一样的数据，那么当前版本号大，就改存当前的。
				try{
					if(performanceReportDetailDO.getVersion() > performanceReportStatisticVersionVOMap.get(performanceReportStatisticVersionVO).getVersion()){
						performanceReportStatisticVersionVOMap.put(performanceReportStatisticVersionVO,performanceReportDetailDO);
					}
				}catch (Exception e){
					throw new BizException(EnumBizError.DATA_OPERATION_ERROR.setErrMsg("存在未存版本号的数据"));
				}
			}
		}
		List<PerformanceReportDetail> performanceReportDetailDOListReturn = new ArrayList<>();
		Set<Map.Entry<PerformanceReportStatisticVersionVO, PerformanceReportDetail>> eset = performanceReportStatisticVersionVOMap.entrySet();
		Iterator<Map.Entry<PerformanceReportStatisticVersionVO, PerformanceReportDetail>> returnList = eset.iterator();
		while (returnList.hasNext()){
			performanceReportDetailDOListReturn.add(returnList.next().getValue());
		}
		return performanceReportDetailDOListReturn;
	}
	private boolean isEq(List<Long>SearchList,List<Long>useList){
		for (Long aLong : SearchList) {
			for (Long aLong1 : useList) {
				if (aLong.longValue()==aLong1.longValue()){
					return true;
				}
			}
		}
		return false;
	}

	private List<Long> getSerchList(List<Long>SearchList,List<Long>useList){
		ArrayList<Long> objects = new ArrayList<>();
		for (Long aLong : SearchList) {
			for (Long aLong1 : useList) {
				if (aLong.longValue()!=aLong1.longValue()){
					objects.add(aLong);
				}
			}
		}
		return objects;
	}


	private List<PerformanceReportDetail> getPerformanceReportDetails(List<Integer> brandTypeList, List<Integer> customerTypeList, List<Integer> monthList, Integer year, List<String> nameList) {
		List<PerformanceReportDetail> performanceReportDetailDOList;
		BooleanBuilder builder =new BooleanBuilder();
		QPerformanceReportDetail qPerformanceReportDetail =QPerformanceReportDetail.performanceReportDetail;
		if (year != null) {
			builder.and(qPerformanceReportDetail.year.eq(year));
		}
		if (brandTypeList!=null && brandTypeList.size()>0){
			builder.and(qPerformanceReportDetail.brandType.in(brandTypeList));
		}
		if (customerTypeList!=null && customerTypeList.size()>0){
			builder.and(qPerformanceReportDetail.customerType.in(customerTypeList));
		}
		if (monthList!=null && monthList.size()>0){
			builder.and(qPerformanceReportDetail.month.in(monthList));
		}
		if (nameList!=null && nameList.size()>0){
			builder.and(qPerformanceReportDetail.employeeName.in(nameList));
		}
		Iterable<PerformanceReportDetail> performanceReportDetails = performanceReportDetailRepository.findAll(builder);
		performanceReportDetailDOList = Lists.newArrayList(performanceReportDetails);
		return performanceReportDetailDOList;
	}

	//按销售人员分类获取净销售额指标
	private List<PerformanceReportSalesVO> getPerformanceReportSalesList(List<PerformanceReportDetail> performanceReportDetailList){
		Map<String,BigDecimal> planSalesMap = new HashMap<>(16);
		Map<String,BigDecimal> actualSalesMap = new HashMap<>(16);
		for(PerformanceReportDetail performanceReportDetailDO : performanceReportDetailList){
			if(performanceReportDetailDO.getStatus() == BizConstants.PerformancePlan.OPERATION_TYPE_REALISTIC){//2为实际销售额
				if (null != performanceReportDetailDO.getSales()){
					if(!actualSalesMap.containsKey(performanceReportDetailDO.getEmployeeName())){
						actualSalesMap.put(performanceReportDetailDO.getEmployeeName(),performanceReportDetailDO.getSales());
					}else {
						BigDecimal total = actualSalesMap.get(performanceReportDetailDO.getEmployeeName()).add(performanceReportDetailDO.getSales());
						actualSalesMap.put(performanceReportDetailDO.getEmployeeName(),total);
					}
				}

			}else if(performanceReportDetailDO.getStatus() == BizConstants.PerformancePlan.OPERATION_TYPE_PLAN){//0为计划销售额
				if(null != performanceReportDetailDO.getSales()){
					if(!planSalesMap.containsKey(performanceReportDetailDO.getEmployeeName())){
						planSalesMap.put(performanceReportDetailDO.getEmployeeName(),performanceReportDetailDO.getSales());
					}else {
						BigDecimal total = planSalesMap.get(performanceReportDetailDO.getEmployeeName()).add(performanceReportDetailDO.getSales());
						planSalesMap.put(performanceReportDetailDO.getEmployeeName(),total);
					}
				}
			}
		}
		List<PerformanceReportSalesVO> performanceReportSalesList = new ArrayList<>();
		BigDecimal actualSalesTotal = null;
		BigDecimal planSalesTotal = null;
		BigDecimal balanceTotal = BigDecimal.ZERO;
		for( String name : planSalesMap.keySet()){//封装
			PerformanceReportSalesVO performanceReportSalesVO = new PerformanceReportSalesVO();
			performanceReportSalesVO.setEmployee(name);
			performanceReportSalesVO.setPlanSales(planSalesMap.get(name));//获取计划销售额
			if(null != planSalesTotal){
				planSalesTotal = planSalesTotal.add(planSalesMap.get(name));//合计计划销售额加上该计划销售额
			}else {
				planSalesTotal = planSalesMap.get(name);
			}

			if(actualSalesMap.containsKey(name)){
				performanceReportSalesVO.setActualSales(actualSalesMap.get(name));
				if(null != actualSalesTotal){
					actualSalesTotal = actualSalesTotal.add(actualSalesMap.get(name));
				}else {
					actualSalesTotal = actualSalesMap.get(name);
				}

				if(actualSalesMap.get(name) != null){
					performanceReportSalesVO.setBalance(actualSalesMap.get(name).subtract(planSalesMap.get(name)));
					balanceTotal = balanceTotal.add(actualSalesMap.get(name).subtract(planSalesMap.get(name)));
					if(planSalesMap.get(name).equals(0)){
						performanceReportSalesVO.setRate(null);
					}else {
						performanceReportSalesVO.setRate(actualSalesMap.get(name).divide(planSalesMap.get(name),4,BigDecimal.ROUND_HALF_UP));//获取达成率
					}
				}
			}
			performanceReportSalesList.add(performanceReportSalesVO);
		}
		if(performanceReportSalesList.size() != 0 && performanceReportDetailList != null){//封装各项数据合计
			PerformanceReportSalesVO performanceReportSalesVO = new PerformanceReportSalesVO();
			performanceReportSalesVO.setEmployee("合计");
			if(null != planSalesTotal && null != actualSalesTotal){
				performanceReportSalesVO.setRate(actualSalesTotal.divide(planSalesTotal,4,BigDecimal.ROUND_HALF_UP));
			}
			performanceReportSalesVO.setBalance(balanceTotal);
			performanceReportSalesVO.setActualSales(actualSalesTotal);
			performanceReportSalesVO.setPlanSales(planSalesTotal);
			performanceReportSalesList.add(performanceReportSalesVO);
		}
		return performanceReportSalesList;
	}

	//按客户类型分类获取净销售额指标
	private List<PerformanceReportCustomerVO> getPerformanceReportCustomerList(List<PerformanceReportDetail> performanceReportDetailList){
		Map<Integer,BigDecimal> planSalesMap = new HashMap<>(16);
		Map<Integer,BigDecimal> actualSalesMap = new HashMap<>(16);
		for(PerformanceReportDetail performanceReportDetailDO : performanceReportDetailList){
			if(performanceReportDetailDO.getStatus() == BizConstants.PerformancePlan.OPERATION_TYPE_REALISTIC){//0为实际销售额
				if(null != performanceReportDetailDO.getSales()){
					if(!actualSalesMap.containsKey(performanceReportDetailDO.getCustomerType())){
						actualSalesMap.put(performanceReportDetailDO.getCustomerType(),performanceReportDetailDO.getSales());
					}else {
						BigDecimal total = actualSalesMap.get(performanceReportDetailDO.getCustomerType()).add(performanceReportDetailDO.getSales());
						actualSalesMap.put(performanceReportDetailDO.getCustomerType(),total);
					}
				}
			}else if(performanceReportDetailDO.getStatus() == BizConstants.PerformancePlan.OPERATION_TYPE_PLAN){//1为计划销售额
				if(null != performanceReportDetailDO.getSales()){
					if(!planSalesMap.containsKey(performanceReportDetailDO.getCustomerType())){
						planSalesMap.put(performanceReportDetailDO.getCustomerType(),performanceReportDetailDO.getSales());
					}else {
						BigDecimal total = planSalesMap.get(performanceReportDetailDO.getCustomerType()).add(performanceReportDetailDO.getSales());
						planSalesMap.put(performanceReportDetailDO.getCustomerType(),total);
					}
				}
			}
		}
		List<PerformanceReportCustomerVO> performanceReportCustomerList = new ArrayList<>();
		BigDecimal customerTotal = null;
		for(Integer customerType :actualSalesMap.keySet() ){//求全国实际销售额
			if(null != customerTotal){
				customerTotal = customerTotal.add(actualSalesMap.get(customerType));
			}else {
				customerTotal = actualSalesMap.get(customerType);
			}
		}
		BigDecimal actualSalesTotal = null;
		BigDecimal planSalesTotal = null;
		BigDecimal balanceTotal = null;
		BigDecimal proportionTotal = null;
		for(Integer customerType : planSalesMap.keySet()){//封装
			PerformanceReportCustomerVO performanceReportCustomerVO = new PerformanceReportCustomerVO();
			if(customerType == BizConstants.PerformancePlan.PROJECT_COLLECTION){//0是集采
				performanceReportCustomerVO .setCustomerType(BizConstants.PerformancePlan.PROJECT_COLLECTION_STR);
			}else if(customerType == BizConstants.PerformancePlan.PROJECT_NOT_COLLECTION){//1是非集采
				performanceReportCustomerVO .setCustomerType(BizConstants.PerformancePlan.PROJECT_NOT_COLLECTION_STR);
			}
			performanceReportCustomerVO.setPlanSales(planSalesMap.get(customerType));
			if(null != planSalesTotal){
				planSalesTotal = planSalesTotal.add(performanceReportCustomerVO.getPlanSales());
			}else {
				planSalesTotal = performanceReportCustomerVO.getPlanSales();
			}

			if(actualSalesMap.containsKey(customerType)){
				performanceReportCustomerVO.setActualSales(actualSalesMap.get(customerType));
				if(null != actualSalesTotal){
					actualSalesTotal = actualSalesTotal.add(performanceReportCustomerVO.getActualSales());
				}else {
					actualSalesTotal = performanceReportCustomerVO.getActualSales();
				}

				if(actualSalesMap.get(customerType) != null){
					performanceReportCustomerVO.setBalance(actualSalesMap.get(customerType).subtract(planSalesMap.get(customerType)));
					if(null != balanceTotal){
						balanceTotal = balanceTotal.add(performanceReportCustomerVO.getBalance());
					}else {
						balanceTotal = performanceReportCustomerVO.getBalance();
					}

					if(planSalesMap.get(customerType).equals(BizConstants.PerformancePlan.PROJECT_COLLECTION)){
						performanceReportCustomerVO.setRate(BigDecimal.ZERO);
					}else {
						performanceReportCustomerVO.setRate(actualSalesMap.get(customerType).divide(planSalesMap.get(customerType),4,BigDecimal.ROUND_HALF_UP));
						performanceReportCustomerVO.setProportion(actualSalesMap.get(customerType).divide(customerTotal,4,BigDecimal.ROUND_HALF_UP));
						if(null != proportionTotal){
							proportionTotal = proportionTotal.add(performanceReportCustomerVO.getProportion());
						}else {
							proportionTotal = performanceReportCustomerVO.getProportion();
						}

					}
				}
			}
			performanceReportCustomerList.add(performanceReportCustomerVO);
		}
		if(performanceReportCustomerList != null && performanceReportCustomerList.size() != 0){
			PerformanceReportCustomerVO performanceReportCustomerVO = new PerformanceReportCustomerVO();
			performanceReportCustomerVO.setCustomerType("合计");
			performanceReportCustomerVO.setActualSales(actualSalesTotal);
			performanceReportCustomerVO.setPlanSales(planSalesTotal);
			performanceReportCustomerVO.setBalance(balanceTotal);
			if(null != actualSalesTotal && null != planSalesTotal){
				performanceReportCustomerVO.setRate(actualSalesTotal.divide(planSalesTotal,4,BigDecimal.ROUND_HALF_UP));
			}
			performanceReportCustomerVO.setProportion(proportionTotal);
			performanceReportCustomerList.add(performanceReportCustomerVO);
		}
		return performanceReportCustomerList;
	}

	//按品牌分类获取净销售额指标
	private List<PerformanceReportBrandVO> getPerformanceReportBrandList(List<PerformanceReportDetail> performanceReportDetailList){
		Map<Integer,BigDecimal> planSalesMap = new HashMap<>(16);
		Map<Integer,BigDecimal> actualSalesMap = new HashMap<>(16);
		for(PerformanceReportDetail performanceReportDetailDO : performanceReportDetailList){
			if(performanceReportDetailDO.getStatus() == BizConstants.PerformancePlan.OPERATION_TYPE_REALISTIC){//0为实际销售额
				if (null != performanceReportDetailDO.getSales()){
					if(!actualSalesMap.containsKey(performanceReportDetailDO.getBrandType())){
						actualSalesMap.put(performanceReportDetailDO.getBrandType(),performanceReportDetailDO.getSales());
					}else {
						BigDecimal total = actualSalesMap.get(performanceReportDetailDO.getBrandType()).add(performanceReportDetailDO.getSales());
						actualSalesMap.put(performanceReportDetailDO.getBrandType(),total);
					}
				}
			}else if(performanceReportDetailDO.getStatus() == BizConstants.PerformancePlan.OPERATION_TYPE_PLAN){//1为计划销售额
				if (null != performanceReportDetailDO.getSales()){
					if(!planSalesMap.containsKey(performanceReportDetailDO.getBrandType())){
						planSalesMap.put(performanceReportDetailDO.getBrandType(),performanceReportDetailDO.getSales());
					}else {
						BigDecimal total = planSalesMap.get(performanceReportDetailDO.getBrandType()).add(performanceReportDetailDO.getSales());
						planSalesMap.put(performanceReportDetailDO.getBrandType(),total);
					}
				}
			}
		}
		List<PerformanceReportBrandVO> performanceReportBrandList = new ArrayList<>();
		BigDecimal brandTotal = null;
		for(Integer brandType :actualSalesMap.keySet() ){//求全国实际销售额
			if(null != brandTotal){
				brandTotal = brandTotal.add(actualSalesMap.get(brandType));
			}else {
				brandTotal = actualSalesMap.get(brandType);
			}

		}
		BigDecimal actualSalesTotal = null;
		BigDecimal planSalesTotal = null;
		BigDecimal balanceTotal = null;
		BigDecimal proportionTotal = null;
		for(Integer brandType : planSalesMap.keySet()){
			PerformanceReportBrandVO performanceReportBrandVO = new PerformanceReportBrandVO();
			if(brandType == 0){
				performanceReportBrandVO.setBrand("VRP");
			}else if(brandType == 1){
				performanceReportBrandVO.setBrand("Wanda");
			}
			performanceReportBrandVO.setPlanSales(planSalesMap.get(brandType));
			if(null != planSalesTotal){
				planSalesTotal = planSalesTotal.add(performanceReportBrandVO.getPlanSales());
			}else {
				planSalesTotal = performanceReportBrandVO.getPlanSales();
			}

			if(actualSalesMap.containsKey(brandType)){
				performanceReportBrandVO.setActualSales(actualSalesMap.get(brandType));
				if(null != actualSalesTotal){
					actualSalesTotal = actualSalesTotal.add(performanceReportBrandVO.getActualSales());
				}else {
					actualSalesTotal = performanceReportBrandVO.getActualSales();
				}

				if(actualSalesMap.get(brandType) != null){
					performanceReportBrandVO.setBalance(actualSalesMap.get(brandType).subtract(planSalesMap.get(brandType)));
					if(null != balanceTotal){
						balanceTotal = brandTotal.add(performanceReportBrandVO.getBalance());
					}else {
						balanceTotal = performanceReportBrandVO.getBalance();
					}

					if(planSalesMap.get(brandType).equals(0)){
						performanceReportBrandVO.setRate(BigDecimal.ZERO);
					}else {
						performanceReportBrandVO.setRate(actualSalesMap.get(brandType).divide(planSalesMap.get(brandType),4,BigDecimal.ROUND_HALF_UP));
						performanceReportBrandVO.setProportion(actualSalesMap.get(brandType).divide(brandTotal,4,BigDecimal.ROUND_HALF_UP));
						if(null != proportionTotal){
							proportionTotal = proportionTotal.add(performanceReportBrandVO.getProportion());
						}else {
							proportionTotal = performanceReportBrandVO.getProportion();
						}

					}
				}
			}
			performanceReportBrandList.add(performanceReportBrandVO);
		}
		if(performanceReportBrandList != null && performanceReportBrandList.size() != 0){
			PerformanceReportBrandVO performanceReportBrandVO = new PerformanceReportBrandVO();
			performanceReportBrandVO.setBrand("合计");
			performanceReportBrandVO.setActualSales(actualSalesTotal);
			performanceReportBrandVO.setPlanSales(planSalesTotal);
			performanceReportBrandVO.setBalance(balanceTotal);
			if(null != actualSalesTotal && null != planSalesTotal){
				performanceReportBrandVO.setRate(actualSalesTotal.divide(planSalesTotal,4,BigDecimal.ROUND_HALF_UP));
			}
			performanceReportBrandVO.setProportion(proportionTotal);
			performanceReportBrandList.add(performanceReportBrandVO);
		}
		return performanceReportBrandList;
	}

	//按年份分类计算各品牌中的各客户类型的选中年份的总销售额和前一年的总销售额以及年增长率
	private List<PerformanceReportComparisonVO> getPerformanceReportComparisonList(List<PerformanceReportDetail> performanceReportDetailList, List<PerformanceReportDetail> performanceReportDetailFormerList){
		Map<String, BigDecimal> currentActualSalesMap = this.actualSalesMap(performanceReportDetailList);//选中年份的实际销售总额
		Map<String, BigDecimal> formerActualSalesMap = new HashMap<>(16);
		if(performanceReportDetailFormerList.size() != 0 && performanceReportDetailFormerList != null){
			formerActualSalesMap = this.actualSalesMap(performanceReportDetailFormerList);//选中年份前一年的实际销售总额
		}
		List<PerformanceReportComparisonVO> performanceReportComparisonList =  new ArrayList<>();
		BigDecimal formerSalesTotal = null;
		BigDecimal currentSalesTotal = null;
		BigDecimal rateTotal = null;
		for(String type : currentActualSalesMap.keySet()){
			PerformanceReportComparisonVO performanceReportComparisonVO = new PerformanceReportComparisonVO();
			performanceReportComparisonVO.setType(type);
			if(currentActualSalesMap.get(type) != null){
				performanceReportComparisonVO.setCurrentSales(currentActualSalesMap.get(type));
				if(null != currentSalesTotal){
					currentSalesTotal = currentSalesTotal.add(performanceReportComparisonVO.getCurrentSales());
				}else {
					currentSalesTotal = performanceReportComparisonVO.getCurrentSales();
				}

			}else {
				performanceReportComparisonVO.setCurrentSales(null);
			}
			if(formerActualSalesMap.containsKey(type) && formerActualSalesMap.get(type) != null){
				performanceReportComparisonVO.setFormerSales(formerActualSalesMap.get(type));
				if (null != formerSalesTotal){
					formerSalesTotal = formerSalesTotal.add(performanceReportComparisonVO.getFormerSales());
				}else {
					formerSalesTotal = performanceReportComparisonVO.getFormerSales();
				}
			}else {
				performanceReportComparisonVO.setFormerSales(null);
			}
			if(null != performanceReportComparisonVO.getFormerSales() && null != performanceReportComparisonVO.getCurrentSales() && !performanceReportComparisonVO.getFormerSales().equals(BigDecimal.ZERO) && !performanceReportComparisonVO.getCurrentSales().equals(BigDecimal.ZERO) ){
				if(performanceReportComparisonVO.getFormerSales().compareTo(performanceReportComparisonVO.getCurrentSales()) == 0){//如果当前年份的销售额等于前一年的销售额，则增长率为0
					performanceReportComparisonVO.setRate(null);
				}else {//不相等，则计算出增长率，可为负数
					BigDecimal raiseNumber = performanceReportComparisonVO.getCurrentSales().subtract(performanceReportComparisonVO.getFormerSales());//增长了多少销售额
					performanceReportComparisonVO.setRate(raiseNumber.divide(performanceReportComparisonVO.getFormerSales()));//增长的部分属于前一年的销售额，为增长率
					if(null != rateTotal){
						rateTotal = rateTotal.add(performanceReportComparisonVO.getRate());
					}else {
						rateTotal = performanceReportComparisonVO.getRate();
					}
				}
			}
			performanceReportComparisonList.add(performanceReportComparisonVO);
		}
		if(performanceReportComparisonList != null && performanceReportComparisonList.size() != 0){
			PerformanceReportComparisonVO performanceReportComparisonVO = new PerformanceReportComparisonVO();
			performanceReportComparisonVO.setType("实际销售总额");
			performanceReportComparisonVO.setFormerSales(formerSalesTotal);
			performanceReportComparisonVO.setCurrentSales(currentSalesTotal);
			performanceReportComparisonVO.setRate(rateTotal);
			performanceReportComparisonList.add(performanceReportComparisonVO);
		}
		return performanceReportComparisonList;
	}

	//此内部方法通过performanceReportDetailList获取当前年份各品牌+各客户类型下的总实际销售额度集合
	private Map<String, BigDecimal> actualSalesMap(List<PerformanceReportDetail> performanceReportDetailList){
		Map<String, BigDecimal> actualSalesMap = new HashMap<>(16);//传入年份的实际销售总额
		for(PerformanceReportDetail performanceReportDetailDO : performanceReportDetailList){//遍历封装选中年份及其销售总额MAP
			if(performanceReportDetailDO.getStatus() == BizConstants.PerformancePlan.OPERATION_TYPE_REALISTIC){//判断是否为实际销售额度
				if(performanceReportDetailDO.getBrandType() == 0){//先判断品牌再判断客户类型，将对应的销售总额封装到Map中
					if(performanceReportDetailDO.getCustomerType() == BizConstants.PerformancePlan.PROJECT_COLLECTION){//如果客户类型为0，则集采
						String type = "VRP" + BizConstants.PerformancePlan.PROJECT_COLLECTION_STR;
						if (null != performanceReportDetailDO.getSales()){
							if(!actualSalesMap.containsKey(type)){
								actualSalesMap.put(type,performanceReportDetailDO.getSales());
							}else {
								actualSalesMap.put(type,actualSalesMap.get(type).add(performanceReportDetailDO.getSales()));
							}
						}
					}else if(performanceReportDetailDO.getCustomerType() == BizConstants.PerformancePlan.PROJECT_NOT_COLLECTION ){//客户类型为1，非集采
						String type = "VRP" + BizConstants.PerformancePlan.PROJECT_NOT_COLLECTION_STR;
						if (null != performanceReportDetailDO.getSales()){
							if(!actualSalesMap.containsKey(type)){
								actualSalesMap.put(type,performanceReportDetailDO.getSales());
							}else {
								actualSalesMap.put(type,actualSalesMap.get(type).add(performanceReportDetailDO.getSales()));
							}
						}
					}
				}else if(performanceReportDetailDO.getBrandType() == 1){
					if(performanceReportDetailDO.getCustomerType() == BizConstants.PerformancePlan.PROJECT_COLLECTION){//如果客户类型为0，则集采
						String type = "Wanda" + BizConstants.PerformancePlan.PROJECT_COLLECTION_STR;
						if (null != performanceReportDetailDO.getSales()){
							if(!actualSalesMap.containsKey(type)){
								actualSalesMap.put(type,performanceReportDetailDO.getSales());
							}else {
								actualSalesMap.put(type,actualSalesMap.get(type).add(performanceReportDetailDO.getSales()));
							}
						}
					}else if(performanceReportDetailDO.getCustomerType() == BizConstants.PerformancePlan.PROJECT_NOT_COLLECTION){//客户类型为1，非集采
						String type = "Wanda" + BizConstants.PerformancePlan.PROJECT_NOT_COLLECTION_STR;
						if (null != performanceReportDetailDO.getSales()){
							if(!actualSalesMap.containsKey(type)){
								actualSalesMap.put(type,performanceReportDetailDO.getSales());
							}else {
								actualSalesMap.put(type,actualSalesMap.get(type).add(performanceReportDetailDO.getSales()));
							}
						}
					}
				}
			}
		}
		return actualSalesMap;
	}
	protected User getCurrentUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		if (principal != null && principal instanceof User) {
			return (User) principal;
		} else {
			Object details = authentication.getDetails();
			if (details != null && details instanceof User) {
				return (User) details;
			}
		}
		return null;
	}
}
